package com.example.shoppingmallspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.shoppingmallspringboot.entity.Cart;
import com.example.shoppingmallspringboot.mapper.CartMapper;
import com.example.shoppingmallspringboot.service.CartService;
import com.example.shoppingmallspringboot.vo.CartVo;
import com.example.shoppingmallspringboot.util.FwResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    
    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<CartVo> getUserCart(Integer userId) {
        List<CartVo> cartList = cartMapper.getGoods();
        Map<Integer, List<CartVo>> map = cartList.stream()
                .collect(Collectors.groupingBy(CartVo::getUserId));
        return map.get(userId);
    }

    @Override
    public FwResult addCart(Cart cart) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", cart.getUserId())
              .eq("goods_id", cart.getGoodsId());
        
        List<Cart> cartList = cartMapper.selectList(wrapper);
        
        if (cartList.size() > 0) {
            Cart existingCart = cartList.get(0);
            UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", existingCart.getUserId())
                        .eq("goods_id", existingCart.getGoodsId());
            
            Integer newQuantity = cart.getQuantity() + existingCart.getQuantity();
            updateWrapper.set("quantity", newQuantity);
            
            cartMapper.update(null, updateWrapper);
            return FwResult.ok("该商品已经在购物车中,数量+1");
        }
        
        cartMapper.insert(cart);
        return FwResult.ok("添加成功");
    }

    @Override
    public FwResult deleteCart(List<Cart> cartList) {
        for (Cart cart : cartList) {
            cartMapper.deleteById(cart.getCartId());
        }
        return FwResult.ok("删除成功");
    }

    @Override
    public void updateQuantity(Cart cart) {
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", cart.getUserId())
                    .eq("goods_id", cart.getGoodsId());
        updateWrapper.set("quantity", cart.getQuantity());
        cartMapper.update(null, updateWrapper);
    }
} 